package com.lsh.controller;

import com.github.pagehelper.PageInfo;
import com.lsh.constants.Constants;
import com.lsh.entity.QueryPageBean;
import com.lsh.entity.Result;
import com.lsh.pojo.Course;
import com.lsh.pojo.User;
import com.lsh.service.CourseService;
import com.lsh.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
public class CourseController {
    @Autowired
    private CourseService courseService;

    /**
     * 增加学科
     * @param course
     * @return
     */
    @PostMapping("/course")
    public Result addCourse(@RequestBody Course course, HttpSession session){
        User user = (User) session.getAttribute(Constants.SESSIONID);
        if (user != null){
            //已经登录状态
            try {
                course.setUserId(user.getId());//设置操作员id
                course.setCreateDate(DateUtils.parseDate2String(new Date()));//设置添加时间
                course.setOrderNo(1);//设置排序
                courseService.addCourse(course);
                return new Result(true,"添加成功");
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false,e.getMessage());
            }
        } else {
            //未登录状态
            return new Result(false,"未登录状态");
        }
    }

    /**
     * 查询所有显示的学科
     * @return
     */
    @GetMapping("/course")
    public Result findAll(Integer status){
        List<Course> courseList = null;
        try {
            courseList = courseService.findAll(status);
            return new Result(true,"查询成功",courseList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,e.getMessage(),courseList);
        }

    }
    /**
     * 分页查询
     * @param queryPageBean
     * @return
     */
    @PostMapping("/course/page")
    public Result findCourse(@RequestBody QueryPageBean queryPageBean){
        PageInfo<Course> coursePageInfo = courseService.findCourse(queryPageBean);
        return new Result(true,"查询成功",coursePageInfo);
    }
    @DeleteMapping("/course")
    public Result delete(Integer id){
        try {
            courseService.delete(id);
            return new Result(true,"删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,e.getMessage());
        }
    }
    @PostMapping("/coures/update")
    public Result update(@RequestBody Course course){
        try {
            courseService.update(course);
            return new Result(true,"更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,e.getMessage());
        }

    }
}
